package com.lin.servlet;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 加载资源文件并从下载
 */
public class ServletDemo2 extends HelloServlet{
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filePath = getServletContext().getRealPath("/WEB-INF/classes/a.png");
        try (
                FileInputStream fis = new FileInputStream(filePath);
                BufferedInputStream bis = new BufferedInputStream(fis)
        ) {
            // 设置下载文件名
            String fileName = "/WEB-INF/classes/a.png";
            //
            resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            int len;
            byte[] bytes = new byte[1024];
            BufferedOutputStream os = new BufferedOutputStream(resp.getOutputStream());
            while ((len = bis.read(bytes)) != -1) {
                os.write(bytes, 0, len);
            }
            os.flush();
        }
    }
//    @Override
//    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        // 动态获取文件路径
//        String filePath = getServletContext().getRealPath("/WEB-INF/classes/a.png");
//        if (filePath == null || !new File(filePath).exists()) {
//            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found.");
//            return;
//        }
//
//        try (
//                FileInputStream fis = new FileInputStream(filePath);
//                BufferedInputStream bis = new BufferedInputStream(fis)
//        ) {
//            // 提取文件名
//            String fileName = new File(filePath).getName();
//
//            // 设置响应头，支持非 ASCII 文件名
//            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
//            resp.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
//
//            // 写入文件内容到响应流
//            byte[] bytes = new byte[1024];
//            BufferedOutputStream os = new BufferedOutputStream(resp.getOutputStream());
//            int len;
//            while ((len = bis.read(bytes)) != -1) {
//                os.write(bytes, 0, len);
//            }
//            os.flush();
//        } catch (FileNotFoundException e) {
//            // 捕获文件未找到异常并返回错误信息
//            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "File could not be read.");
//        } catch (IOException e) {
//            // 捕获其他 IO 异常并返回错误信息
//            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while reading the file.");
//        }
//    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
